<script>
import { GetUserCoupons } from '@/api/homePage.js';
import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";

export default {
  name: "coupons",
  components: {HzSafeArea},
  data() {
    return {
      businessId: '',
      totalPrice: 0,
      productId: '',
      shopCoupon: [],
      allCoupon: [],
      isChangeShop: -1,
      isChangeAll: -1,
      selectedCoupons: []
    }
  },
  onLoad(options) {
    // 解析传入参数
    if (options && options.params) {
      try {
        const params = JSON.parse(decodeURIComponent(options.params));
        this.businessId = params.businessId || '';
        this.totalPrice = parseFloat(params.totalPrice) || 0;
        this.productId = params.productId || '';
        
        // 初始化已选择的优惠券
        if (params.selectedCoupons && Array.isArray(params.selectedCoupons)) {
          this.selectedCoupons = params.selectedCoupons;
          
          // 如果有已选择的优惠券，设置对应的索引值
          this.updateSelectedIndexes();
        }
      } catch (e) {
        console.error('解析参数错误:', e);
      }
    }

    // 设置导航栏标题
    uni.setNavigationBarTitle({title: this.$t('coupons.title')});
    
    // 获取优惠券数据
    this.getCoupon();
  },
  methods: {
    // 获取用户优惠券
    async getCoupon() {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        const { Data } = await GetUserCoupons({
          Index: 1,
          Size: 100,
          BusinessId: this.businessId,
          CouponStatus: 1
        });
        
        uni.hideLoading();
        
        if (!Data || !Array.isArray(Data)) {
          console.warn('获取优惠券返回数据格式异常');
          return;
        }
        
        const currentDate = Date.now();
        
        // 分类并筛选未过期的优惠券
        const validCoupons = Data.reduce((result, coupon) => {
          const startTime = Date.parse(coupon.EffectStartDatetime);
          const endTime = Date.parse(coupon.EffectEndDatetime);
          
          if (currentDate < endTime && currentDate > startTime) {
            // 添加可用状态
            coupon.isDisabled = coupon.CouponTemple.MinimumConsumption > this.totalPrice;
            
            if (!coupon.BusinessIds) {
              result.platform.push(coupon);
            } else {
              result.shop.push(coupon);
            }
          }
          
          return result;
        }, { shop: [], platform: [] });
        
        this.shopCoupon = validCoupons.shop;
        this.allCoupon = validCoupons.platform;
        
        // 获取优惠券数据后，更新已选择的优惠券索引
        if (this.selectedCoupons.length > 0) {
          this.$nextTick(() => {
            this.updateSelectedIndexes();
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('获取优惠券失败:', error);
        uni.showToast({
          title: this.$t('coupons.loadFailed'),
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 选择商家优惠券
    selectCoupon(index, item) {
      if (item.isDisabled) {
        uni.showToast({
          title: this.$t('coupons.insufficientAmount'),
          icon: 'none',
          duration: 2000
        });
        return;
      }
      if (index !== this.isChangeShop) {
        this.isChangeShop = index;
        this.isChangeAll = -1; // 取消平台券选择
        this.selectedCoupons = [item]; // 只保留当前商家券
      } else {
        this.isChangeShop = -1;
        this.selectedCoupons = [];
      }
    },
    
    // 选择平台优惠券
    selectAllCoupon(index, item) {
      if (item.isDisabled) {
        uni.showToast({
          title: this.$t('coupons.insufficientAmount'),
          icon: 'none',
          duration: 2000
        });
        return;
      }
      if (index !== this.isChangeAll) {
        this.isChangeAll = index;
        this.isChangeShop = -1; // 取消商家券选择
        this.selectedCoupons = [item]; // 只保留当前平台券
      } else {
        this.isChangeAll = -1;
        this.selectedCoupons = [];
      }
    },
    
    // 确认选择
    confirmSelection() {
      // 计算优惠券折扣总金额
      const totalDiscount = this.selectedCoupons.reduce((sum, coupon) => {
        return sum + (coupon.CouponTemple.FullReduceAmount || 0);
      }, 0);
      
      // 页面返回
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2]; // 获取上一页实例
      
      if (prevPage && prevPage.$vm) {
        // 调用上一页的回调方法
        prevPage.$vm.onCouponSelected(this.selectedCoupons);
        
        // 返回上一页
        uni.navigateBack();
        
        // 提示用户
        if (this.selectedCoupons.length > 0) {
          uni.showToast({
            title: this.$t('coupons.selectSuccess', {count: this.selectedCoupons.length, amount: totalDiscount}),
            icon: 'none',
            duration: 2000
          });
        }
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 更新已选优惠券的索引值
    updateSelectedIndexes() {
      // 重置索引
      this.isChangeShop = -1;
      this.isChangeAll = -1;
      // 只允许选一张券
      if (this.selectedCoupons.length > 0) {
        const selectedCoupon = this.selectedCoupons[0];
        if (selectedCoupon.BusinessIds) {
          // 商家券
          const shopIndex = this.shopCoupon.findIndex(coupon => 
            coupon.CouponCode === selectedCoupon.CouponCode
          );
          if (shopIndex !== -1) {
            this.isChangeShop = shopIndex;
          }
        } else {
          // 平台券
          const allIndex = this.allCoupon.findIndex(coupon => 
            coupon.CouponCode === selectedCoupon.CouponCode
          );
          if (allIndex !== -1) {
            this.isChangeAll = allIndex;
          }
        }
      }
    }
  }
}
</script>

<template>
  <view class="coupon-container">
    <!-- 商家优惠券 -->
    <view class="coupon-section" v-if="shopCoupon.length > 0">
      <view class="section-title">{{ $t('coupons.merchant') }}</view>
      <view class="coupon-list">
        <view 
          v-for="(item, index) in shopCoupon" 
          :key="index"
          class="coupon-box"
          :style="{'--item-index': index}"
          @click="selectCoupon(index, item)"
        >
          <view class="coupon-item" :class="{'active-coupon': isChangeShop === index, 'disabled-coupon': item.isDisabled}">
            <view class="cuoponLeft couponTop2">
              <view class="price">
                ￥<text>{{item.CouponTemple.FullReduceAmount}}</text>
              </view>
              <view class="type">
                <view class="useWhere">{{ $t('coupons.merchantTag') }}</view>
              </view>
            </view>
            <view class="cuoponRight">
              <view class="name">{{item.CouponTemple.CouponName || $t('coupons.merchantTag')}}</view>
              <view class="bot_right">
                <view class="all_j">{{ $t('coupons.condition', {amount: item.CouponTemple.MinimumConsumption}) }}</view>
                <view class="time">{{ $t('coupons.validity', {start: item.EffectStartDatetime.substring(0, 10), end: item.EffectEndDatetime.substring(0, 10)}) }}</view>
              </view>
              <view class="coupon-check" v-if="isChangeShop === index">
                <uni-icons type="checkbox-filled" size="20" color="#0099FF"></uni-icons>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 平台优惠券 -->
    <view class="coupon-section" v-if="allCoupon.length > 0">
      <view class="section-title">{{ $t('coupons.platform') }}</view>
      <view class="coupon-list">
        <view 
          v-for="(item, index) in allCoupon" 
          :key="index"
          class="coupon-box"
          :style="{'--item-index': index}"
          @click="selectAllCoupon(index, item)"
        >
          <view class="coupon-item" :class="{'active-coupon': isChangeAll === index, 'disabled-coupon': item.isDisabled}">
            <view class="cuoponLeft couponTop4">
              <view class="price">
                ￥<text>{{item.CouponTemple.FullReduceAmount}}</text>
              </view>
              <view class="type">
                <view class="useWhere">{{ $t('coupons.platformTag') }}</view>
              </view>
            </view>
            <view class="cuoponRight">
              <view class="name">{{item.CouponTemple.CouponName || $t('coupons.platformTag')}}</view>
              <view class="bot_right">
                <view class="all_j">{{ $t('coupons.condition', {amount: item.CouponTemple.MinimumConsumption}) }}</view>
                <view class="time">{{ $t('coupons.validity', {start: item.EffectStartDatetime.substring(0, 10), end: item.EffectEndDatetime.substring(0, 10)}) }}</view>
              </view>
              <view class="coupon-check" v-if="isChangeAll === index">
                <uni-icons type="checkbox-filled" size="20" color="#0099FF"></uni-icons>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 无优惠券提示 -->
    <view class="empty-coupon" v-if="shopCoupon.length === 0 && allCoupon.length === 0">
      <image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
      <view class="empty-text">{{ $t('coupons.empty') }}</view>
    </view>
    <hz-safe-area background="#F5F6F7"></hz-safe-area>

    <!-- 底部确认按钮 -->
    <view class="bottom-bar">
      <view class="bottom-bar-inner">
        <view class="selected-info">
          {{ $t('coupons.selected', {count: selectedCoupons.length}) }}
        </view>
        <view class="confirm-btn" @click="confirmSelection">{{ $t('coupons.confirm') }}</view>
      </view>
      <hz-safe-area></hz-safe-area>
    </view>
  </view>
</template>

<style scoped lang="scss">
// 定义全局变量
$primary-color: #0099FF;
$primary-gradient: linear-gradient(135deg, #00BFFF 0%, #0099FF 100%);
$text-primary: #333;
$text-secondary: #666;
$text-light: #999;
$background-light: #F5F6F7;
$background-white: #FFF;
$border-radius: 16rpx;
$padding-common: 30rpx;
$margin-bottom: 20rpx;
$font-small: 24rpx;
$font-medium: 28rpx;
$font-large: 32rpx;
$font-xlarge: 36rpx;

.coupon-container {
  min-height: 100vh;
  background-color: $background-light;
  padding: 24rpx;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

.coupon-section {
  margin-bottom: 30rpx;
  
  .section-title {
    padding: 20rpx 0;
    font-size: $font-medium;
    color: $text-secondary;
    font-weight: 500;
  }
}

.coupon-box {
  position: relative;
  margin-bottom: 24rpx;
  animation: fadeInUp 0.5s ease forwards;
  animation-delay: calc(0.1s * var(--item-index, 0));
  will-change: transform, opacity;
  
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(30rpx);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
}

.coupon-item {
  background-color: #fff;
  width: 100%;
  height: 220rpx;
  border-radius: $border-radius;
  display: flex;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    left: 32%;
    top: 0;
    bottom: 0;
    width: 2rpx;
    background: radial-gradient(circle at center, #f0f0f0 0, #f0f0f0 2rpx, transparent 3rpx);
    background-size: 2rpx 12rpx;
    background-repeat: repeat-y;
  }
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
  }
  
  &.active-coupon {
    box-shadow: 0 4rpx 20rpx rgba(0, 153, 255, 0.2);
  }
  
  &.disabled-coupon {
    opacity: 0.6;
  }
  
  .cuoponLeft {
    width: 32%;
    height: 100%;
    color: #fff;
    text-align: center;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    
    .price {
      font-size: 28rpx;
      font-weight: 500;
      line-height: 1;
      margin-bottom: 16rpx;
      
      text {
        font-size: 64rpx;
        font-weight: 600;
        margin-left: 4rpx;
      }
    }
    
    .type {
      .useWhere {
        font-size: 26rpx;
        background: rgba(255, 255, 255, 0.2);
        padding: 4rpx 16rpx;
        border-radius: 20rpx;
      }
    }
  }
  
  .cuoponRight {
    width: 68%;
    height: 100%;
    padding: 32rpx;
    position: relative;
    box-sizing: border-box;
    
    .name {
      font-size: 32rpx;
      color: #333;
      font-weight: 600;
      margin-bottom: 16rpx;
      line-height: 1.4;
    }
    
    .bot_right {
      color: #999;
      font-size: 24rpx;
      line-height: 1.6;
      
      .all_j {
        margin-bottom: 8rpx;
      }
      
      .time {
        color: #666;
      }
    }
    
    .coupon-check {
      position: absolute;
      right: 32rpx;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}

.couponTop2, .couponTop4 {
  background: $primary-gradient;
}

.empty-coupon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: $font-medium;
    color: $text-light;
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: $background-white;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
  
  .bottom-bar-inner {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    height: 100rpx;
  }
  
  .selected-info {
    font-size: $font-medium;
    color: $text-secondary;
    
    .highlight {
      color: $primary-color;
      font-weight: bold;
    }
  }
  
  .confirm-btn {
    background: $primary-gradient;
    color: $background-white;
    font-size: $font-medium;
    padding: 20rpx 60rpx;
    border-radius: 40rpx;
    font-weight: 500;
  }
}
</style>